package com.xcx.robot.mirai.listener;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.xcx.robot.mirai.QuickStart;
import com.xcx.robot.mirai.config.UserConfig;
import com.xcx.robot.mirai.factory.BaseFacade;
import com.xcx.robot.mirai.factory.MessageFactory;
import com.xcx.robot.mirai.factory.facade.RecallFacade;
import com.xcx.robot.mirai.factory.notaop.TalkFacade;
import com.xcx.robot.mirai.jxapi.Result;
import com.xcx.robot.mirai.key.KeyWord;
import com.xcx.robot.mirai.util.ImageForRobot;
import com.xcx.robot.mirai.util.KeyUtils;
import com.xcx.robot.mirai.util.SenderHelper;
import com.xcx.robot.util.ChatBot;
import com.xcx.robot.util.ImageUtils;
import lombok.extern.slf4j.Slf4j;
import net.mamoe.mirai.contact.Contact;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.contact.Member;
import net.mamoe.mirai.contact.NormalMember;
import net.mamoe.mirai.data.GroupHonorType;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.SimpleListenerHost;
import net.mamoe.mirai.event.events.*;
import net.mamoe.mirai.message.MessageReceipt;
import net.mamoe.mirai.message.data.At;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.message.data.PlainText;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * @Author: 邢晨旭
 * @Date: 2021/5/19 20:49
 * @Description: TODO 拆分成多个listener(高内聚，低耦合)
 */
@Slf4j
@Component
public class MyListener extends SimpleListenerHost {

    @Value("${robot.flag}")
    Integer flag;

    @Resource
    UserConfig userConfig;

    @Resource
    MessageFactory messageFactory;

    @Resource
    ImageForRobot saveImage;

    @Resource
    ChatBot chatBot;

    @Resource
    TalkFacade talkFacade;

    /**
     * 群消息监听处理
     *
     * @param event
     */
    @EventHandler
    public void onGroupMessage(GroupMessageEvent event) {
        Group group = event.getGroup();
        Member sender = event.getSender();
        RecallFacade.recall.computeIfAbsent(group.getId(), k -> new ArrayList<>());
        String content = event.getMessage().contentToString();
        KeyWord keyWord = KeyWord.groupFind(KeyUtils.getKeyByWord(content, 1));
        BaseFacade messageFacade = null;
        if (userConfig.getExcludeList().stream().noneMatch(qq -> qq.equals(group.getId()))) {
            messageFacade = messageFactory.get(keyWord);
            if (messageFacade != null) {
                messageFacade.execute(sender, group, content);
            }
            return;
        } else {
            if (content.contains("扶摇") && content.contains("开启") && !content.contains("触发") && !content.contains("跑啦") && !content.contains("跑惹") && !content.contains("跑掉")) {
                At at = new At(542648926);
                Contact contact = QuickStart.bot.getGroup(346252812);
                SenderHelper.sendMessage(contact, at.plus(event.getMessage()));
            }
        }
        String s = event.getMessage().contentToString();
        if (event.getMessage().get(At.Key) != null && !s.matches(".*\\[.*\\].*")) {
            //TODO 线程池 智障聊天
//            log.info("event.getMessage().get(PlainText.Key){}",event.getMessage().get(PlainText.Key));
//            log.info("event.getMessage().get(PlainText.Key){}",event.getMessage().get(PlainText.Key).contentToString());
            talkFacade.talk(sender, group, s);
        } else {
            //智障聊天
            int i = new Random().nextInt(100);
//            log.info("随机数{}", i);

            if (i >= flag && StringUtils.isNotEmpty(s) && !s.matches(".*\\[.*\\].*")) {
//            String s = HttpUtil.get("https://jx3api.com/extend/expression?format=text");
//            log.info("随机图片{}", s);
//            Image r = group.uploadImage(Objects.requireNonNull(ImageUtils.initImage(s)));
                String talk = chatBot.talk(s);
                if (StringUtils.isEmpty(talk)) {
                    return;
                }
                MessageReceipt messageReceipt = group.sendMessage(talk);
                List<MessageReceipt> receipts = RecallFacade.recall.get(group.getId());
                if (receipts.size() > 20) {
                    receipts.clear();
                }
//            MemberNudge nudge = sender.nudge();
//            nudge.sendTo(group);
                RecallFacade.recall.get(group.getId()).add(messageReceipt);
            }
        }

        //聊天图片保存 TODO 线程池
        saveImage.save(event);

    }
    //https://jx3api.com/extend/expression?format=text

    /**
     * 入群事件监听
     *
     * @param event
     */
    @EventHandler
    public void onMemberJoin(MemberJoinEvent event) {
        NormalMember joinMember = event.getMember();
        At at = new At(joinMember.getId());
        NormalMember invitor = null;
        At at2 = null;
        StringBuilder result = new StringBuilder();

        //被邀请入群
        if (event instanceof MemberJoinEvent.Invite) {
            invitor = ((MemberJoinEvent.Invite) event).getInvitor();
            at2 = new At(invitor.getId());
            result.append("(●'◡'●)邀请的小可爱");
        } else {
            result.append("(●'◡'●)欢迎小可爱");
        }
        String url = "";
        int i = new Random().nextInt(10);
        if (i == 4) {
            url = GROUP_JOIN2;
        } else {
            url = String.format(GROUP_JOIN, i);
        }
        Image image = event.getGroup().uploadImage(ImageUtils.initImage(url));
        PlainText plainText = new PlainText("");
        if (at2 != null) {
            SenderHelper.sendMessage(event.getGroup(), plainText.plus(at2).plus(result).plus(at).plus("来啦").plus("\n改下id哦(职业+昵称)").plus(image));
        } else {
            SenderHelper.sendMessage(event.getGroup(), plainText.plus(at).plus(result).
                    plus("\n改下id哦(职业+昵称)").plus(image));
        }
    }

    String GROUP_JOIN = "https://jx3kt.oss-cn-shanghai.aliyuncs.com/group/group%s.jpg";
    String GROUP_JOIN2 = "https://jx3kt.oss-cn-shanghai.aliyuncs.com/group/group.gif";
    String GROUP_DRAGON_KING = "https://jx3kt.oss-cn-shanghai.aliyuncs.com/group/GroupDragonKing%s.png";

    /**
     * 群荣誉变更
     *
     * @param event
     */
    @EventHandler
    public void onMemberHonorChange(MemberHonorChangeEvent event) {
        NormalMember member = event.getMember();
        Group group = event.getGroup();
        GroupHonorType honorType = event.getHonorType();
        switch (honorType) {
            case TALKATIVE:
                log.info("群荣誉变更{}", "龙王");
                group.sendMessage(new At(member.getId()).plus("新-大水比"));
                break;
            case PERFORMER:
                log.info("群荣誉变更{}", "群聊之火");
                break;
            case LEGEND:
                log.info("群荣誉变更{}", "群聊炽焰");
                break;
            case STRONG_NEWBIE:
                log.info("群荣誉变更{}", "冒尖小春笋");
                break;
            case EMOTION:
                log.info("群荣誉变更{}", "快乐源泉");
                break;
            case ACTIVE:
                log.info("群荣誉变更{}", "活跃头衔");
                break;
            case EXCLUSIVE:
                log.info("群荣誉变更{}", "特殊头衔");
                break;
            case MANAGE:
                log.info("群荣誉变更{}", "管理头衔");
                break;
            default:
                return;
        }
        if (event instanceof MemberHonorChangeEvent.Achieve) {
            log.info("群荣誉变更{}", "Achieve");
            group.sendMessage(group.uploadImage(Objects.requireNonNull(ImageUtils.initImage(String.format(GROUP_DRAGON_KING, new Random().nextInt(10))))));
        }
        if (event instanceof MemberHonorChangeEvent.Lose) {
            log.info("群荣誉变更{}", "Lose");
        }
        //Mirai.getInstance().getRawGroupHonorListData((Bot) member,event.getGroup().getId(),honorType);
    }


    @EventHandler
    public void onFriendMessage(FriendMessageEvent event) {
        String s = HttpUtil.get("https://jx3api.com/app/macro?name=北傲诀");
        event.getSender().sendMessage(JSONObject.parseObject(s, Result.class).getData().getCommand());
    }

    @EventHandler
    public void onBotLeaveEvent(BotLeaveEvent event) {
        event.getBot().login();
    }


}
